<?php

namespace App\Exports;

use App\Models\Config;
use Dcat\Admin\Grid\Exporters\ExcelExporter;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Lang;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Style\Border;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class DyExporter extends AbstractExporter implements ShouldAutoSize,WithEvents,WithHeadings,FromArray,WithTitle
{
    use Exportable;

    protected $fileName;
    protected $activity_signups;
    protected $data_count_all;
    public $team;
    public $relation_model;
    public $relation_service;
    public $group_columns;
    public $universal_fields;
    public $last_row_number = 0; // 列数，最后一列的编号数字 0 =>A, 1 => B 。。。。
    public $last_col_number = 3; // 行数，开始有数据的编号，如果有的表不同，在____construct中根据表名修改这个数字
    public $merge_cells = [];
    public $title;
    public $modelClass;
    public $edit_fields;
    public $links_config;
    public $table;
    public $admin_user;
    public $setNumberFormatTextColumns = [];
    public $customColumnWidth = []; # 定义特殊列宽

    public function __construct($modelClass, $admin_user = null)
    {
        $this->admin_user = $admin_user;
        $this->modelClass = $modelClass;
        $this->table = (new $this->modelClass)->getTable();

        $this->links_config = collect(Config::getLinks())->where('table', $this->table)->first();
        if (!$this->links_config) {
            throw new Exception('导出错误');
        }
        $this->title = $this->links_config['title'];


        # 文件名称
        $filter_dwmc = request()->get('dwmc');
        if($filter_dwmc != ''){
            $this->fileName = $filter_dwmc . '_' . $modelClass::NAME . date("ymdhis") .".xlsx";
        }else{
            $dwmc = $this->admin_user ? $this->admin_user->dwmc : '';
            if  ($dwmc) {
                $this->fileName = $dwmc . '_' . $modelClass::NAME . date("ymdhis") .".xlsx";
            } else {
                $this->fileName = $modelClass::NAME . date("ymdhis") .".xlsx";
            }
        }
        # 表头字段
        $this->edit_fields = $modelClass::$edit_fields;
    }

    public function headings(): array
    {
        $table = $this->table;
        $links_config = $this->links_config;

        $title = $this->title;
        if (isset($links_config['second_title']) && $links_config['second_title']) {
            $title .= " " . $links_config['second_title'];
        }
        $headers = [[$title]];

        $_subheaders = ['序号', '院级党组织名称'];
        $trans = Lang::get($links_config['trans'] . '.fields');
        $edit_fields = $this->edit_fields;
        $k = 1;
        foreach($edit_fields as $field) {
            $_title = isset($trans[$field]) ? $trans[$field] : $field;
            array_push($_subheaders, $_title);
//            if ($field == 'sfz') {
//                // $this->setNumberFormatTextColumns[] = int3ExcelLetter($k);
//                array_push($this->customColumnWidth, ['column' => $k, 'width' => 35]); # 特殊列宽
//            }

//            if (in_array($field, ['dzzmc', 'gzdwzw'])) {
//                array_push($this->customColumnWidth, ['column' => $k, 'width' => 50]);
//            }
//            if (in_array($field, ['dzb'])) {
//                array_push($this->customColumnWidth, ['column' => $k, 'width' => 65]);
//            }
            $k++;
        }
        #第一列序号定宽
        array_push($this->customColumnWidth, ['column' => 'A', 'width' => 12]);
        $headers[] = $_subheaders;
        $this->last_row_number = count($_subheaders);
        $this->last_col_number = count($headers);

        # 合并表头的数据，标题
        array_push($this->merge_cells, 'A1:' . int3ExcelLetter($this->last_row_number-1) . '1');
        if($table == 'dzz_yjdzz_infos'){    #表7 院级党组织所属党总支名册
            $headers[] = ['','','','','','','','姓名', '性别', '民族', '工作岗位', '学历学位', '职务职称'];
            array_push($this->merge_cells, 'H2:M2');
            array_push($this->merge_cells, 'A2:A3');
            array_push($this->merge_cells, 'B2:B3');
            array_push($this->merge_cells, 'C2:C3');
            array_push($this->merge_cells, 'D2:D3');
            array_push($this->merge_cells, 'E2:E3');
            array_push($this->merge_cells, 'F2:F3');
            array_push($this->merge_cells, 'G2:G3');
            $headers[1][7] = '党总支书记信息';
            $this->last_col_number = $this->last_col_number + 1;
        }elseif($table == 'dzz_infos'){ #表8 党支部名册
            $headers[] = ['','','','','','','','','联系教师姓名','参加活动次数','姓名', '性别', '民族', '工作岗位', '学历学位', '职务职称'];
            array_push($this->merge_cells, 'I2:J2');
            array_push($this->merge_cells, 'K2:P2');
            array_push($this->merge_cells, 'A2:A3');
            array_push($this->merge_cells, 'B2:B3');
            array_push($this->merge_cells, 'C2:C3');
            array_push($this->merge_cells, 'D2:D3');
            array_push($this->merge_cells, 'E2:E3');
            array_push($this->merge_cells, 'F2:F3');
            array_push($this->merge_cells, 'G2:G3');
            array_push($this->merge_cells, 'H2:H3');
            $headers[1][8] = '联系支部情况';
            $headers[1][10] = '党总支书记信息';
            $this->last_col_number = $this->last_col_number + 1;
        }elseif($table == 'dy_cgjs'){ #表8 出国（境）党员名册
            $headers[] = ['','','','','','','','','公派出国（境）半年以上','因私出国(境)半年以上','本年自费留学出国（境）', '本年出国（境）定居'];
            $headers[1][8] = '出国(境)半年以上';
            $headers[1][10] = '本年出国（境）';
            array_push($this->merge_cells, 'I2:J2');
            array_push($this->merge_cells, 'K2:L2');
            array_push($this->merge_cells, 'A2:A3');
            array_push($this->merge_cells, 'B2:B3');
            array_push($this->merge_cells, 'C2:C3');
            array_push($this->merge_cells, 'D2:D3');
            array_push($this->merge_cells, 'E2:E3');
            array_push($this->merge_cells, 'F2:F3');
            array_push($this->merge_cells, 'G2:G3');
            array_push($this->merge_cells, 'H2:H3');
            $this->last_col_number = $this->last_col_number + 1;
        }
        return $headers;
    }

    public function export()
    {
        // TODO: Implement export() method.
        $this->download($this->fileName)->prepare(request())->send();
        exit;
    }

    public function title(): string
    {
        return $this->title;
    }

    public function array(): array
    {
        $is_super_manger = $this->admin_user->isSuperManger();

        $build_data = [];
        $base_query = $this->modelClass::query();
        if ($is_super_manger) { # 如果是组织部人员
            if(!in_array($this->table, ['dzz_yjdzz_infos', 'dzz_infos', 'dy_hfdjs', 'dy_tzdjs','dy_ld'])){
                $base_query->where('is_main', 1);
            }
        } else {
            $base_query->where('dwdm', $this->admin_user->dwdm);
        }

        $filter_data = request()->except(['_pjax', '_export_']);
        if(isset($filter_data['dwmc']) && $filter_data['dwmc'] != ''){
            $base_query->where('dwmc', $filter_data['dwmc']);
        }
        if(isset($filter_data['export_order']) && $filter_data['export_order'] != ''){
            if($filter_data['export_order'] == 1){
                $base_query->orderBy('dwdm');
            }elseif($filter_data['export_order'] == 2){
                $base_query->orderBy('created_at');
            }
        }

        $datas = $base_query->get();
        foreach($datas as $key => $data) {
            $row = [($key + 1), $data->dwmc];
            foreach($this->edit_fields as $field) {
                if (in_array($field, ['sfz', 'xuegonghao', 'zjhm'])) {
                    $row[] = $data->$field."\t";
                } else {
                    $row[] = $data->$field;
                }
                
            }
            array_push($build_data, $row);
            $this->last_col_number++;
        }
        return $build_data;
    }


    public function registerEvents(): array
    {
        return [
            AfterSheet::class  => function(AfterSheet $event) {
                // foreach($this->setNumberFormatTextColumns as $column) {
                //     $event->sheet->getDelegate()->getStyle($column.'1:'.$column.$this->last_col_number)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                // }

                $borders = [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_THIN,
                        'color' => [
                            'rgb' => '000000'
                        ]
                    ],
                ];
                $font = [
                    'name' => '宋体',
                    'bold' => false,
                    'size' => 11,
                    'italic' => false,
                    'strikethrough' => false,
                    'color' => [
                        'rgb' => '000000'
                    ]
                ];


                $customColumnWidthNumbers = collect($this->customColumnWidth)->pluck('column')->all();
                for($i=0; $i<$this->last_row_number;$i++) {
                    if (in_array($i, $customColumnWidthNumbers)) {
                        continue;
                    }
                    $event->sheet->getDelegate()->getColumnDimension(int3ExcelLetter($i))->setAutoSize(false)->setWidth(20);
                }
                # 特殊列宽
                foreach($this->customColumnWidth as $value) {
                    $event->sheet->getDelegate()->getColumnDimension(int3ExcelLetter($value['column']))->setAutoSize(false)->setWidth($value['width']);
                }

                for($i=1; $i<=$this->last_col_number;$i++) {
                    $event->sheet->getDelegate()->getRowDimension($i)->setRowHeight(23);
                }

                foreach($this->merge_cells as $merge_cell) {
                    $event->sheet->getDelegate()->mergeCells($merge_cell);//合并单元格
                }
                

                $event->sheet->getDelegate()->getStyle("A1:".(int3ExcelLetter($this->last_row_number-1).($this->last_col_number)))->getAlignment()->setVertical('center')->setHorizontal('center')->setWrapText(TRUE);
                $event->sheet->getDelegate()->getStyle('A1:'.(int3ExcelLetter($this->last_row_number-1).($this->last_col_number)))->applyFromArray([
                    'font' => $font,
                    'borders' => $borders
                ]);

                //第一行居中，标题
                $first_font = $font;
                $first_font['size'] = '20';
                $first_font['bold'] = true;
                $event->sheet->getDelegate()->getStyle("A1:".(int3ExcelLetter($this->last_row_number-1).'1'))->getAlignment()->setVertical('center')->setHorizontal('center')->setWrapText(TRUE);
                $event->sheet->getDelegate()->getStyle("A1:".(int3ExcelLetter($this->last_row_number-1).'1'))
                ->applyFromArray([
                    'font' => $first_font
                ]);
                $event->sheet->getDelegate()->getRowDimension(1)->setRowHeight(40);

                $second_font = $font;
                $second_font['size'] = '11';
                $second_font['bold'] = true;
                $event->sheet->getDelegate()->getStyle("A2:".(int3ExcelLetter($this->last_row_number-1).'2'))
                ->applyFromArray([
                    'font' => $second_font
                ]);
                if (in_array($this->table, ['dy_cgjs', 'dzz_infos', 'dzz_yjdzz_infos'])) {
                    $event->sheet->getDelegate()->getStyle("A3:".(int3ExcelLetter($this->last_row_number-1).'3'))
                    ->applyFromArray([
                        'font' => $second_font
                    ]);
                }
            }
        ];
    }

    private function pad_empty_string($value) {
        return '  ' . $value . '  ';
    }
}